"""
任务模型
包含:
1. JobModel - 任务
2. JobExecutionLogModel - 任务执行日志
3. JobChangeLogModel - 任务变更日志
"""

from tortoise import fields

from app.core.constants import ChangeType, ExecutionStatus, ExecutorType, TaskStatus, TriggerType
from app.models.base_model import BaseModel, SoftDeleteModel


class JobModel(SoftDeleteModel):
    name = fields.CharField(max_length=255, description="任务名称")
    description = fields.CharField(max_length=255, null=True, description="任务描述")

    # 类型
    executor_type = fields.IntEnumField(ExecutorType, default=ExecutorType.MODULE, description="执行器类型")
    # 支持执行脚本
    script_path = fields.CharField(max_length=512, null=True, description="脚本路径")
    # 支持执行模块
    module_path = fields.CharField(max_length=255, description="模块路径，例如: apps.task.test.example_job")
    function_name = fields.CharField(max_length=255, description="函数名称，例如: example_job")
    trigger_type = fields.IntEnumField(TriggerType, description="触发器类型")
    trigger_args = fields.JSONField(description="触发器参数 如: {'interval': 10}")
    args = fields.JSONField(null=True, description="函数参数 如: ['参数1', '参数2']")
    kwargs = fields.JSONField(null=True, description="函数关键字参数 如: {'key1': 'value1', 'key2': 'value2'}")
    timeout = fields.FloatField(null=True, default=60.0, description="超时时间 单位: 秒")
    status = fields.IntEnumField(TaskStatus, default=TaskStatus.ACTIVE, description="任务状态")
    priority = fields.IntField(default=0, description="优先级")

    # 创建者
    creator = fields.ForeignKeyField(
        "models.UserModel", related_name="created_jobs", through="task_job_to_user", null=True
    )

    class Meta:
        table = "jobs"


class JobExecutionLogModel(BaseModel):
    job = fields.ForeignKeyField("models.JobModel", related_name="execution_logs", description="关联的任务")
    status = fields.IntEnumField(ExecutionStatus, description="执行状态")  # 执行中、成功、失败、超时
    result = fields.JSONField(null=True, description="执行结果")
    error_message = fields.TextField(null=True, description="错误信息")
    traceback = fields.TextField(null=True, description="错误堆栈")
    duration = fields.DecimalField(max_digits=10, decimal_places=5, null=True, description="执行时长(秒)")

    start_time = fields.DatetimeField(description="开始执行时间")
    end_time = fields.DatetimeField(null=True, description="结束执行时间")

    class Meta:
        table = "job_execution_logs"


class JobChangeLogModel(BaseModel):
    job = fields.ForeignKeyField("models.JobModel", related_name="change_logs", description="关联的任务")
    change_type = fields.IntEnumField(ChangeType, description="修改类型")  # 创建、更新、删除、暂停、恢复
    changed_fields = fields.JSONField(description="修改的字段")  # {"field_name": {"old_value": xxx, "new_value": xxx}}
    operator = fields.ForeignKeyField("models.UserModel", related_name="job_changes", description="操作人", null=True)
    remark = fields.TextField(null=True, description="备注")

    class Meta:
        table = "job_change_logs"
